package com.wyw.learning.thread.lock.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 演示lockInterruptibly
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * @date 2021/7/14   10:47 下午
 * <p>
 * Update History:
 * Author        Time            Content
 */
public class LockInterruptibly implements Runnable {

    private Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        LockInterruptibly lockInterruptibly = new LockInterruptibly();
        Thread thread0 = new Thread(lockInterruptibly);
        Thread thread1 = new Thread(lockInterruptibly);
        thread0.start();
        thread1.start();
        Thread.sleep(2000);
//        thread0.interrupt();//释放
        thread1.interrupt();//释放

    }


    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "尝试获得锁");
        try{
            lock.lockInterruptibly();
            System.out.println(Thread.currentThread().getName() + "获得锁");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + "睡眠锁期间被打断");
            } finally {
                lock.unlock();
                System.out.println(Thread.currentThread().getName() + "释放锁");
            }
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + "获得锁期间被打断");
        }
    }
}
